﻿using System.Text;
using System.Text.Json;

namespace WorkTool2.Helpers;

public static class JsonValidationHelper
{
    private static readonly JsonDocumentOptions DocumentOptions = new JsonDocumentOptions
    {
        CommentHandling = JsonCommentHandling.Skip,
        AllowTrailingCommas = true
    };

    /// <summary>
    /// 综合JSON验证方法（支持注释）
    /// </summary>
    public static JsonValidationResult ValidateJsonWithComments(string input)
    {
        if (string.IsNullOrWhiteSpace(input))
            return new JsonValidationResult { IsValid = false, Error = "Input is null or empty" };

        input = input.Trim();

        // 快速结构检查
        if (!((input.StartsWith('{') && input.EndsWith('}')) ||
              (input.StartsWith('[') && input.EndsWith(']'))))
        {
            return new JsonValidationResult
            {
                IsValid = false,
                Error = "JSON must start with '{' or '[' and end with '}' or ']"
            };
        }

        try
        {
            byte[] jsonBytes = Encoding.UTF8.GetBytes(input);
            using (JsonDocument document = JsonDocument.Parse(jsonBytes, DocumentOptions))
            {
                return new JsonValidationResult
                {
                    IsValid = true,
                    JsonType = GetJsonType(document),
                    ElementCount = GetElementCount(document)
                };
            }
        }
        catch (JsonException ex)
        {
            return new JsonValidationResult
            {
                IsValid = false,
                Error = ex.Message
            };
        }
        catch (Exception ex)
        {
            return new JsonValidationResult
            {
                IsValid = false,
                Error = $"Unexpected error: {ex.Message}"
            };
        }
    }

    /// <summary>
    /// 去除JSON中的注释
    /// </summary>
    public static string RemoveComments(string jsonWithComments)
    {
        if (string.IsNullOrWhiteSpace(jsonWithComments))
            return jsonWithComments;

        try
        {
            byte[] jsonBytes = Encoding.UTF8.GetBytes(jsonWithComments);
            using (JsonDocument document = JsonDocument.Parse(jsonBytes, DocumentOptions))
            {
                // 重新序列化以去除注释
                return JsonSerializer.Serialize(document.RootElement, new JsonSerializerOptions
                {
                    WriteIndented = true
                });
            }
        }
        catch
        {
            return jsonWithComments;
        }
    }

    private static JsonType GetJsonType(JsonDocument document)
    {
        return document.RootElement.ValueKind switch
        {
            JsonValueKind.Object => JsonType.Object,
            JsonValueKind.Array => JsonType.Array,
            _ => JsonType.Unknown
        };
    }

    private static int GetElementCount(JsonDocument document)
    {
        return document.RootElement.ValueKind switch
        {
            JsonValueKind.Object => document.RootElement.GetPropertyCount(),
            JsonValueKind.Array => document.RootElement.GetArrayLength(),
            _ => 0
        };
    }
}

public enum JsonType
{
    Object,
    Array,
    Unknown
}

public class JsonValidationResult
{
    public bool IsValid { get; set; }
    public string Error { get; set; }
    public JsonType JsonType { get; set; }
    public int ElementCount { get; set; }
}